<template>
  <PageWrapper dense contentFullHeight contentClass="flex">
    <DeptTreeList class="w-1/4 xl:w-1/5 treeList" @select="handleSelect" />
    <div
      class="m-4 w-3/4 xl:w-4/5"
      v-show="canAdminDept || curDeptCode == 'root'"
      style="border-radius: 8px"
    >
      <Card
        :headStyle="{ padding: '0 16px' }"
        :bodyStyle="{ padding: 0 }"
        :tab-list="tabListNoTitle"
        :active-tab-key="noTitleKey"
        @tab-change="(key) => onTabChange(key)"
        class="h-full"
        style="border-radius: 8px"
      >
        <p v-show="noTitleKey === '1'">
          <BasicTable
            @register="registerTable"
            :searchInfo="searchInfo"
            @resize-column="handleResizeColumn"
            :beforeEditSubmit="beforeEditSubmit"
            @edit-end="handleEditEnd"
            @edit-cancel="handleEditCancel"
          >
            <template #toolbar v-if="canAdminDept">
              <Popconfirm
                placement="bottom"
                :title="isSyncWxToOA ? '确定从微信同步吗？' : '确定同步至微信吗？'"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleSynWx"
              >
                <a-button type="primary" size="middle" v-if="isUseWx" :loading="isWxSyn"
                  >微信同步</a-button
                >
              </Popconfirm>
              <Popconfirm
                placement="bottom"
                :title="isSyncDingDingToOA ? '确定从钉钉同步吗？' : '确定同步至钉钉吗？'"
                ok-text="确定"
                cancel-text="取消"
                @confirm="handleSynDd"
              >
                <a-button type="primary" size="middle" v-if="isUseDingDing" :loading="isDdSyn"
                  >钉钉同步</a-button
                >
              </Popconfirm>
              <a-button type="primary" size="middle" @click="handleCreate">新增</a-button>
              <a-button type="primary" size="middle" @click="handleOut">调出</a-button>
              <a-button type="primary" size="middle" @click="handleIn">调入</a-button>
              <a-button type="primary" size="middle" @click="handleExport" :loading="isExport"
                >导出</a-button
              >
              <a-button type="primary" size="middle" @click="handleImport">导入</a-button>

              <Modal v-model:visible="importVisible" title="导入" :closable="true">
                <template #footer>
                  <a-button @click="handleCancel">关闭</a-button>
                </template>
                <div style="padding: 20px">
                  <Row>
                    <Col :span="8">
                      <a-button
                        type="primary"
                        @click="handleDownloadExcelTempl"
                        :loading="isDownload"
                        >下载模板</a-button
                      >
                    </Col>
                    <Col :span="8">
                      <ImpExcel :isFiles="false" @raw-file="rawFileFn" dateFormat="YYYY-MM-DD">
                        <a-button type="primary" :loading="isImport">导入</a-button>
                      </ImpExcel>
                    </Col>
                  </Row>
                </div>
              </Modal>

              <!-- <ImpExcel :isFiles="false" @raw-file="rawFileFn" dateFormat="YYYY-MM-DD">
                <a-button type="primary" size="middle" :loading="isImport">导入</a-button>
              </ImpExcel> -->
              <Popconfirm
                placement="bottom"
                title="确定删除吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="getSelectRowKeyList"
              >
                <a-button type="primary" size="middle">删除</a-button>
              </Popconfirm>
              <!-- <Popconfirm title="您确定要根据角色中的人员排序来刷新人员总排序么" ok-text="确定" cancel-text="取消" @confirm="handleRefreshOrder(d)">
                <a-button type="primary" size="middle">排序</a-button>
              </Popconfirm> -->
            </template>
            <template #action="{ record }">
              <TableAction
                :actions="[
                  {
                    icon: 'clarity:note-edit-line',
                    tooltip: '编辑用户资料',
                    onClick: handleEdit.bind(null, record),
                  },
                  {
                    icon: 'ant-design:delete-outlined',
                    color: 'error',
                    tooltip: '删除此账号',
                    popConfirm: {
                      title: '是否确认删除',
                      placement: 'leftBottom',
                      confirm: handleDelete.bind(null, record),
                    },
                  },
                ]"
                :dropDownActions="[
                  {
                    label: '角色',
                    onClick: handleActions.bind(null, record, 'role'),
                  },
                  {
                    label: '权限',
                    onClick: handleActions.bind(null, record, 'jur'),
                  },
                  {
                    label: '分管部门',
                    onClick: handleActions.bind(null, record, 'dept'),
                  },
                  {
                    label: '复位',
                    onClick: handleResetFlag.bind(null, record),
                  },
                ]"
              />
            </template>
          </BasicTable>
        </p>
        <p v-show="noTitleKey === '2'">
          <Position ref="positionRef" />
        </p>
      </Card>
    </div>
    <div
      class="flex flex-col justify-center bg-white w-full m-4"
      v-show="!canAdminDept && curDeptCode != 'root'"
    >
      <Empty>
        <template #description>
          <span> 您没有权限浏览 </span>
        </template>
      </Empty>
    </div>
    <OrganizationManagementDrawer @register="registerDrawer" @success="handleSuccess" />
    <UserJurInfo @register="userJurInfoDrawer" />
    <UserDeptInfo @register="userDeptInfoDrawer" />
    <UserRoleInfo @register="userRoleInfoDrawer" @success="handleSuccess" />
    <CallOutDrawer @register="callOutDrawer" @success="handleSuccess" />
    <SelectUser @register="registerModal" @success="handleInSave" />
  </PageWrapper>
</template>
<script lang="ts">
  import { defineComponent, reactive, ref, unref, onMounted, watchEffect, h, nextTick } from 'vue';

  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getUserList,
    getUserDelUsers,
    getTransferUsers,
    getExportUser,
    getUserImportFinish,
    getUserImportConfirm,
    getConfigInfo,
    synAll,
    checkCanAdminDept,
    getUserOrdersEditInPlace,
    getDownloadUserImportTemplate,
    refreshAllUserOrder,
    resetUserAttackFlag,
  } from '/@/api/system/system';
  import { PageWrapper } from '/@/components/Page';
  import { Popconfirm, Card, Empty, Modal, Row, Col } from 'ant-design-vue';
  import { useDrawer } from '/@/components/Drawer';
  import OrganizationManagementDrawer from './organizationManagementDrawer.vue';

  import { columns, searchFormSchema, cardTabList, isChange } from './organizationManagement.data';
  // import { useGo } from '/@/hooks/web/usePage';
  import Position from './position/index.vue';
  import DeptTreeList from './deptTreeList.vue';
  import UserJurInfo from './modules/userJurInfo/userJurInfo.vue';
  import UserDeptInfo from './modules/userDeptInfo/userDeptInfo.vue';
  import UserRoleInfo from './modules/userRoleInfo/userRoleInfo.vue';
  import CallOutDrawer from './modules/callOutDrawer.vue';
  import { useModal } from '/@/components/Modal';
  import { SelectUser } from '/@/components/CustomComp';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { downloadByData } from '/@/utils/file/download';
  import { ImpExcel } from '/@/components/Excel';
  import { useI18n } from '/@/hooks/web/useI18n';

  export default defineComponent({
    name: 'OrganizationManagement',
    components: {
      BasicTable,
      PageWrapper,
      DeptTreeList,
      OrganizationManagementDrawer,
      TableAction,
      Card,
      Position,
      UserJurInfo,
      UserDeptInfo,
      UserRoleInfo,
      CallOutDrawer,
      SelectUser,
      Popconfirm,
      ImpExcel,
      Empty,
      Modal,
      Row,
      Col,
    },
    setup() {
      // const go = useGo();
      const { t } = useI18n();

      let selectRows = ref([]);
      const { createMessage, createConfirm } = useMessage();
      const positionRef = ref<null | HTMLElement>(null);
      const isExport = ref(false);
      const isImport = ref(false);
      let key = ref('1');
      let noTitleKey = ref('1');
      const [registerDrawer, { openDrawer }] = useDrawer();
      const curDeptCode = ref('root');
      // , isValid: '1', op: 'search'
      const searchInfo = reactive<Recordable>({ deptCode: curDeptCode.value });
      const isUseWx = ref(false);
      const isSyncWxToOA = ref(false);
      const isUseDingDing = ref(false);
      const isSyncDingDingToOA = ref(false);
      const isWxSyn = ref(false);
      const isDdSyn = ref(false);
      const canAdminDept = ref(true);
      const isPostUsed = ref(true);
      const tableColumns = ref(columns);
      const isDownload = ref(false);
      const importVisible = ref(false);

      const [
        registerTable,
        { reload, getSelectRowKeys, setSelectedRowKeys, setProps, setColumns },
      ] = useTable({
        title: '人员列表',
        api: getUserList,
        immediate: false,
        rowKey: 'id',
        columns: tableColumns.value,
        showIndexColumn: false,
        formConfig: {
          labelWidth: 60,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        useSearchForm: true,
        showTableSetting: true,
        bordered: true,
        rowSelection: {
          type: 'checkbox',
        },
        searchInfo: {
          op: 'search',
          deptCode: curDeptCode.value,
        }, //额外的参数
        canResize: true,
        // resizeHeightOffset: 50,
        actionColumn: {
          width: 160,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
        pagination: {
          pageSize: 50,
        },
      });

      function handleCreate() {
        openDrawer(true, {
          isUpdate: false,
          record: {
            deptCode: curDeptCode.value,
          },
        });
      }

      function handleEdit(record) {
        openDrawer(true, {
          record,
          isUpdate: true,
        });
      }

      function getSelectRowKeyList() {
        let keys = getSelectRowKeys();
        if (keys.length == 0) {
          createMessage.warning('请选择数据');
          return;
        }
        getUserDelUsers({ ids: keys.join(',') }).then(() => {
          handleSuccess();
        });
      }

      async function handleDelete(record) {
        await getUserDelUsers({ ids: record.user.id }).then(() => {
          handleSuccess();
        });
      }

      function handleSelect(deptId = '', node) {
        console.log('deptId', deptId, 'node', node);
        searchInfo.deptCode = deptId;
        curDeptCode.value = deptId;

        checkCanAdminDept({ deptCode: deptId }).then((res) => {
          canAdminDept.value = res.canAdminDept;
          setTabList();

          if (canAdminDept.value || deptId == 'root') {
            console.log('noTitleKey', noTitleKey.value);
            if (noTitleKey.value == '1') {
              setProps({ searchInfo: { op: 'search', deptCode: searchInfo.deptCode } });
              reload();

              if (deptId == 'root') {
                let cols = tableColumns.value.filter((item) => {
                  return item.dataIndex !== 'deptOrder';
                });
                console.log('checkCanAdminDept cols', cols);
                setColumns(cols);
              } else {
                let cols = tableColumns.value.filter((item) => {
                  return item.dataIndex !== 'orders';
                });
                console.log('checkCanAdminDept cols2', cols);
                setColumns(cols);
              }
            } else if (noTitleKey.value == '2') {
              console.log('handleSelect positionRef', positionRef.value);
              positionRef.value?.fromRef(searchInfo.deptCode);
            }
          }
        });
      }

      const setTabList = () => {
        if (canAdminDept.value && isPostUsed.value) {
          tabListNoTitle.value = cardTabList;
        } else {
          if (!isPostUsed.value) {
            tabListNoTitle.value = [];
          } else {
            if (curDeptCode.value != 'root') {
              tabListNoTitle.value = cardTabList.slice(0, 1);
            } else {
              tabListNoTitle.value = cardTabList;
            }
          }
        }
      };

      function handleActions(record, type) {
        switch (type) {
          case 'role':
            createUserRoleInfoDrawer(record);
            break;
          case 'jur':
            createUserJurInfoDrawer(record);
            break;
          case 'dept':
            createUserDeptInfoDrawer(record);
            break;
          default:
            break;
        }
      }
      //角色
      const [userRoleInfoDrawer, { openDrawer: openDrawerUserRole }] = useDrawer();
      function createUserRoleInfoDrawer(record) {
        openDrawerUserRole(true, {
          record,
        });
      }

      //权限
      const [userJurInfoDrawer, { openDrawer: openDrawerUserJur }] = useDrawer();
      function createUserJurInfoDrawer(record) {
        openDrawerUserJur(true, {
          record,
        });
      }
      //部门
      const [userDeptInfoDrawer, { openDrawer: openDrawerUserDept }] = useDrawer();
      function createUserDeptInfoDrawer(record) {
        openDrawerUserDept(true, {
          record,
        });
      }

      //调出
      const [callOutDrawer, { openDrawer: openDrawerCallOut }] = useDrawer();
      function createCallOutoDrawer(selectRows) {
        openDrawerCallOut(true, {
          record: { ids: selectRows },
        });
      }
      //调出点击
      function handleOut() {
        selectRows.value = getSelectRowKeys() as any;
        if (unref(selectRows).length === 0) {
          createMessage.warning('请选择人员');
          return;
        }
        createCallOutoDrawer(unref(selectRows));
      }
      //调入
      const [registerModal, { openModal }] = useModal();
      function handleIn() {
        openModal(true, {
          isUpdate: false,
        });
      }

      //导出
      async function handleExport() {
        isExport.value = true;
        let excel = await getExportUser();
        try {
          await downloadByData(excel, '全部人员.xls');
        } finally {
          isExport.value = false;
        }
      }

      //获取files
      function rawFileFn(files) {
        let formData = new FormData();
        formData.append('att1', files);
        isImport.value = true;
        getUserImportConfirm(formData).then((res) => {
          if (res.res != 0) {
            createMessage.warn(h('pre', res.msg));
            isImport.value = false;
            return;
          }
          let successArr = res.successArr;
          getUserImportFinish({ info: JSON.stringify(successArr) }).then(() => {
            createMessage.success('操作成功');
            handleSuccess();
            isImport.value = false;
          });
        });
      }

      async function handleInSave(data) {
        if (data && data.length > 0) {
          let userNames = data.map((item) => item.name).join(',');
          let params = {
            deptCode: searchInfo.deptCode,
            userNames: userNames,
          };
          await getTransferUsers(params);
          await handleSuccess();
        }
      }

      function handleSuccess() {
        setSelectedRowKeys([]);
        reload();
      }
      // function handleView(record: Recordable) {
      //   go('/system/account_detail/' + record.id);
      // }
      const tabListNoTitle = ref<any>([]);
      const onTabChange = async (value: string) => {
        noTitleKey.value = value;
        await nextTick();
        if (value == '1') {
          setProps({ searchInfo: { op: 'search', deptCode: searchInfo.deptCode } });
          reload();
        } else if (value == '2') {
          positionRef.value.fromRef(searchInfo.deptCode);
          console.log(value, '--', searchInfo.deptCode);
          console.log('onTabChange searchInfo.deptCode', searchInfo.deptCode);

          handleSelect(searchInfo.deptCode);
        }
      };

      watchEffect(() => {
        if (isChange.value) {
          handleSuccess();
          isChange.value = false;
        }
      }); //监听启用成功后isChange为true时刷新列表

      onMounted(async () => {
        // window.handleSuccess = handleSuccess;
        await getIsPostUsedInfo();
        await checkCanAdminDept({ deptCode: curDeptCode.value }).then((res) => {
          canAdminDept.value = res.canAdminDept;
          setTabList();
        });

        let cols = tableColumns.value.filter((item) => {
          return item.dataIndex !== 'deptOrder';
        });
        setColumns(cols);

        reload();
      });

      function getIsPostUsedInfo() {
        getConfigInfo().then((res) => {
          let is = res.isPostUsed;
          isPostUsed.value = is;
          tabListNoTitle.value = is ? cardTabList : [];

          isUseWx.value = res.isUseWx;
          isSyncWxToOA.value = res.isSyncWxToOA;
          isUseDingDing.value = res.isUseDingDing;
          isSyncDingDingToOA.value = res.isSyncDingDingToOA;
        });
      }

      function handleSynWx() {
        isWxSyn.value = true;
        let op = isSyncWxToOA.value ? 'syncWeixinToOA' : 'syncWeixin';
        synAll({ op })
          .then((data) => {
            if (data.res == 0) {
              createMessage.success('操作成功');
            }
          })
          .finally(() => {
            isWxSyn.value = false;
          });
      }

      function handleSynDd() {
        isDdSyn.value = true;
        let op = isSyncDingDingToOA.value ? 'syncDingdingToOA' : 'syncOAToDingding';
        synAll({ op })
          .then((data) => {
            if (data.res == 0) {
              createMessage.success('操作成功');
            }
          })
          .finally(() => {
            isDdSyn.value = false;
          });
      }

      // -----------------------------------------------------------单元格编辑开始----------------------------------------------------
      function handleEditEnd({ record, index, key, value }: Recordable) {
        console.log('handleEditEnd', record, index, key, value);
        return false;
      }

      function handleEditCancel() {
        console.log('cancel');
      }

      async function beforeEditSubmit({ record, index, key, value }) {
        console.log('单元格数据正在准备提交', { record, index, key, value });
        return await feakSave({
          id: record.id,
          key,
          value,
          deptCode: curDeptCode.value,
          userName: record.user.name,
        });
      }

      // 模拟将指定数据保存
      function feakSave({ value, key, id, deptCode, userName }) {
        // createMessage.loading({
        //   content: `正在保存${key}`,
        //   key: '_save_fake_data',
        //   duration: 0,
        // });
        let params = {
          colName: key,
          id: id,
          update_value: value,
          deptCode,
          userName,
          // original_value:'',
          // original_html:''
        };

        return new Promise((resolve) => {
          getUserOrdersEditInPlace(params).then(() => {
            reload();
            resolve(true);
          });
        });
      }
      // -----------------------------------------------------------单元格编辑结束 ----------------------------------------------------

      function handleDownloadExcelTempl() {
        isDownload.value = true;
        getDownloadUserImportTemplate({}).then((data) => {
          isDownload.value = false;
          let title = '用户导入模板';
          if (data) {
            downloadByData(data, `${title}.xls`);
          }
        });
      }

      function handleImport() {
        importVisible.value = true;
      }

      //导入modal取消
      function handleCancel() {
        importVisible.value = false;
      }

      async function handleRefreshOrder() {
        await refreshAllUserOrder();
        createMessage.success('操作成功');
      }

      function handleResetFlag(record) {
        createConfirm({
          iconType: 'info',
          title: () => h('span', t('common.prompt')),
          content: () => h('span', '您确定要复位么，复位后用户将可以登录系统'),
          onOk: async () => {
            resetUserAttackFlag({ userName: record.user.name }).then(() => {
              createMessage.success('操作成功');
            });
          },
        });
      }

      return {
        registerTable,
        registerDrawer,
        handleCreate,
        handleEdit,
        handleDelete,
        handleSuccess,
        handleSelect,
        // handleView,
        searchInfo,
        tabListNoTitle,
        noTitleKey,
        onTabChange,
        getSelectRowKeyList,
        handleActions,
        userJurInfoDrawer,
        userDeptInfoDrawer,
        userRoleInfoDrawer,
        handleOut,
        callOutDrawer,
        registerModal,
        handleIn,
        handleInSave,
        positionRef,
        handleExport,
        rawFileFn,
        isExport,
        isImport,
        isUseWx,
        isUseDingDing,
        handleSynWx,
        handleSynDd,
        isWxSyn,
        isDdSyn,
        isSyncWxToOA,
        isSyncDingDingToOA,
        handleResizeColumn: (w, col) => {
          col.width = w;
        },
        canAdminDept,
        curDeptCode,
        handleEditEnd,
        handleEditCancel,
        beforeEditSubmit,
        handleDownloadExcelTempl,
        isDownload,
        importVisible,
        handleImport,
        handleCancel,
        handleRefreshOrder,
        handleResetFlag,
      };
    },
  });
</script>
<style lang="less" scoped>
  ::v-deep .ant-btn-sm {
    font-size: 14px !important;
  }
  ::v-deep .vben-basic-table-form-container .ant-form {
    padding: 0;
    margin-bottom: 10px;
  }
  ::v-deep .vben-basic-table-form-container {
    padding-bottom: 0;
  }
</style>
